
#include "projectHeader.h"

//Refrence taken from URL 1)http://www.cplusplus.com/reference/clibrary/cctype/isspace/
//						  2)http://www.cplusplus.com/reference/clibrary/cctype/isupper/
//						  3)http://www.cplusplus.com/reference/clibrary/cctype/tolower/

//Reference--->http://www.engiblogger.com/programming/c-cpp/methods-for-remove-leading-trailing-all-white-spaces-using-c-cpp/
/*void remAllWhiteSpaces(char *str)
{
           int i = 0;
           char *ptr = str;
           for(i = 0; i < strlen(str) || *ptr == '\0'; )
           {
                 if(*ptr == ' ')
                 {
                      strcpy(ptr, ptr + 1);
                      continue;
                 }
                  else
                 {
                      i++;
                      ptr++;
                 }
            }
}
*/
//To do if time permits : removing all white space and handle double inverted.


// End of refered code..
void initParse()
{
 
	//printf("Inside initParse.\n\n");
	
	bool initFlag=false;
	bool beaconFlag=false;
	char fileReadDataBuf[100];
	char * fileReadDataBufModified=NULL;
	FILE *initFile;
	if((initFile=fopen(configFileName,"r"))==NULL) /* opening the file library3*/
	{
		//printf("ERROR:\t%s file cannot be read.\n",configFileName);
		
		exit(1);
	}
	//printf("file opening.\n");


//	printf("Parsing Configuration file.\n");





	while( fgets(fileReadDataBuf,sizeof(fileReadDataBuf),initFile))
	{
		//printf("original String Read is %s and Length is %d.\n\n",fileReadDataBuf,strlen(fileReadDataBuf));
		remLeadingSpaces(fileReadDataBuf);
		//printf("String Read is %s and Length is %d.\n\n",fileReadDataBuf,strlen(fileReadDataBuf));
		fileReadDataBufModified=removeTrailingWhiteSpace(fileReadDataBuf);
		//	fileReadDataBufModified=fileReadDataBuf;
		//printf("String Read is %s and Length is %d.\n\n",fileReadDataBufModified,strlen(fileReadDataBufModified));
		
		if(strncmp(fileReadDataBufModified,"[init]",6)==0)
		{
		//	printf("init section Detected.\n");
			initFlag=true;
			beaconFlag=false;
			continue;
		}
		else if(strncmp(fileReadDataBufModified,"[beacons]",9)==0)
		{
		//	printf("beacon section Detected.\n");
			initFlag=false;
			beaconFlag=true;
			continue;
		
		}
		else if(strncmp(fileReadDataBufModified,"",1)==0)
		{
			continue;	
			
		}
		else
		{}
		
		if(initFlag)
		{
			//printf("Key detected for init section.\n");
			//printf("String Read is %s and Length is %d.\n\n",fileReadDataBufModified,strlen(fileReadDataBufModified));
			

			//================Parse all the Key=Value pair for Init Section=============///
			

			if((strncmp(fileReadDataBufModified,"port",4)==0) && !portFlag)  // Parse the  Port Param.
			{
				
				char *key=NULL;
				key=strtok(fileReadDataBufModified,"=");
		//		printf("Key:  %s\n",key);
				char *value=strtok(NULL,"=");
				port= atoi(value);
		//		printf("Port: %d\n",port);
				portFlag=true;
				
			}
			else if((strncmp(fileReadDataBufModified,"location",8)==0) && !locFlag)  // Parse the Location param.
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					location= atoi(value);
		//			printf("Location: %u\n",location);
					locFlag=true;
			}
			else if((strncmp(fileReadDataBufModified,"logfilename",11)==0) && !logFileFlag)   //Parse the LogFileName Param.
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					logFileName=strtok(NULL,"=");
					
		//			printf("LogFileName: %s\n",logFileName);
					logFileFlag=true;
			}
			

			else if((strncmp(fileReadDataBufModified,"homedir",7)==0) && !homedirFlag) 	// Parse the Homedir Param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char* value=(char*)strtok(NULL,"=");
					memset(homeDir,'\0',512);
					memcpy(homeDir,value,strlen(value));
		//			printf("HomeDir: %s\n",homeDir);
					struct stat st;
					//http://www.daemon-systems.org/man/opendir.3.html
					//http://www.dreamincode.net/forums/topic/27741-create-directory-using-c/
					
					DIR* dirPtr = NULL;
					if(stat(homeDir,&st) < 0)
					{
						printf("Home diretory %s is not present. Node will terminate\n",homeDir);
						exit(1);
					}
					else
					{
						if(S_ISDIR(st.st_mode))
						{
							if((dirPtr = opendir(homeDir)) == NULL)
							{
								printf("Couldn't open directory.  Node will terminate\n");
								//file = NULL;
								exit(1);
							}
						}
						else
						{
							printf("\nGiven location is not a directory.  Node will terminate\n");
							exit(1);
						}
					}

					homedirFlag=true;
			}
			else if((strncmp(fileReadDataBufModified,"autoshutdown",12)==0) && !autoshutFlag)     // Parse the autoshutdown param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					autoShutDown= atoi(value);
		//			printf("AutoShutDowm: %d\n",autoShutDown);
					autoshutFlag=true;
			}

			else if((strncmp(fileReadDataBufModified,"ttl",3)==0) && !ttlFlag) 		// Parse the TTL param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					ttl= atoi(value);
		//			printf("TTL: %d\n",ttl);
					ttlFlag=true;
			}
			else if((strncmp(fileReadDataBufModified,"msglifetime",11)==0) && !msgLifeTimeFlag) 	//Parse MsgLifeTime param
			{
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					msgLifeTime= atoi(value);
		//			printf("MsgLifeTime: %d\n",msgLifeTime);
					msgLifeTimeFlag=true;


			}
			else if((strncmp(fileReadDataBufModified,"minneighbors",12)==0) && !minNeighbourFlag) 	//Parse minNeighbour param
			{

				
				char *key=NULL;
				key=strtok(fileReadDataBufModified,"=");
		//		printf("Key:  %s\n",key);
				char *value=strtok(NULL,"=");
				minNeighbour= atoi(value);
		//		printf("minNeighbour: %d\n",minNeighbour);
				minNeighbourFlag=true;
	
			}
			else if((strncmp(fileReadDataBufModified,"getmsglifetime",14)==0) && !getMsgLifeTimeFlag)   //Parse getMsgLifeTime param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					getMsgLifeTime= atoi(value);
		//			printf("getMsgLifeTime: %d\n",getMsgLifeTime);
					getMsgLifeTimeFlag=true;
			}


			else if((strncmp(fileReadDataBufModified,"initneighbors",13)==0) && !initNeighbourFlag)      // Parse the InitNeighbour param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					initNeighbour= atoi(value);
		//			printf("initNeighbour: %d\n",initNeighbour);
					initNeighbourFlag=true;
			}

			else if((strncmp(fileReadDataBufModified,"jointimeout",11)==0) && !joinTimeOutFlag) 	//// Parse the joinTimeOut param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					joinTimeOut= atoi(value);
		//			printf("joinTimeOut: %d\n",joinTimeOut);
					joinTimeOutFlag=true;
			}

			else if((strncmp(fileReadDataBufModified,"keepalivetimeout",16)==0) && !keepAliveTimeoutFlag)     // Parse the KeepAliveTimeout param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					keepAliveTimeOut= atoi(value);
		//			printf("keepAliveTimeOut: %d\n",keepAliveTimeOut);
					keepAliveTimeoutFlag=true;
			}


			else if((strncmp(fileReadDataBufModified,"nocheck",7)==0) && !noCheckFlag) // Parse the noCheck param
			{					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					noCheck= atoi(value);
		//			printf("noCheck: %d\n",noCheck);
					noCheckFlag=true;
			}
			else if((strncmp(fileReadDataBufModified,"neighborstoreprob",17)==0) && !neighborStoreProbFlag) 		// Parse the NeighborStoreProb param
			{				
				char *key=NULL;
				key=strtok(fileReadDataBufModified,"=");
		//		printf("Key:  %s\n",key);
				char *value=strtok(NULL,"=");
				neighbourStoreProb= atof(value);
		//		printf("neighbourStoreProb: %f\n",neighbourStoreProb);
				neighborStoreProbFlag=true;
			}
			else if((strncmp(fileReadDataBufModified,"cacheprob",9)==0) && !cacheProbFlag) // Parse the cacheProb param
			{
				
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					cacheProb= atof(value);
		//			printf("cacheProb: %f\n",cacheProb);
					cacheProbFlag=true;
			}
			else if((strncmp(fileReadDataBufModified,"cachesize",9)==0) && !cacheSizeFlag) 		// Parse the CacheSize param
			{
				
				char *key=NULL;
				key=strtok(fileReadDataBufModified,"=");
		//		printf("Key:  %s\n",key);
				char *value=strtok(NULL,"=");
				cacheSize= atoi(value);
				cacheSizeInBytes=cacheSize*1024;
				remainingCacheSizeInBytes=cacheSize*1024;

		//		printf("cacheSize: %d\n",cacheSize);
				cacheSizeFlag=true;
			
			}

			else if((strncmp(fileReadDataBufModified,"storeprob",9)==0) && !storeProbFlag) 		// Parse the StoreProb param
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					storeProb= atof(value);
		//			printf("storeProb: %f\n",storeProb);
					storeProbFlag=true;
			}
			
			else
			{
				//printf("ERROR: Invalid Parameter for init Section.\n\n\n");
			}


		}
		else if(beaconFlag)
		{
			//printf("Key detected for beacon section.\n");
			//printf("String Read is %s and Length is %d.\n\n",fileReadDataBufModified,strlen(fileReadDataBufModified));

			//================Parse all the Key=Value pair for Beacon Section=============///
			if((strncmp(fileReadDataBufModified,"retry",5)==0) && !retryFlag) 
			{
					
					char *key=NULL;
					key=strtok(fileReadDataBufModified,"=");
		//			printf("Key:  %s\n",key);
					char *value=strtok(NULL,"=");
					retry= atoi(value);
		//			printf("retry: %d\n",retry);
					retryFlag=true;

			}
			else	// Parse the beacon node host:prt pairs
			{
					char *temp=NULL;
					temp=strtok(fileReadDataBufModified,"=");
		//			printf("Temp:  %s\n",temp);
					char *key1=strtok(temp,":");
					//printf("Key:  %s\n",key);
					char *value=strtok(NULL,":");
					int portNum= atoi(value);
					//printf("retry: %d\n",retry);
					//retryFlag=true;
					hostPort p=hostPort(key1,value);

					if((strncmp(myHostName,key1,sizeof(myHostName))==0) && (portNum==port))
					{
						//printf("\n\n\nI AM THE BEACON NODE YAAAY!! \n\n\n");
						iAmBeacon=true;
					}
					else
					{
						if(!softRestartFlag)
							beaconList.push_back(p);
					}
			}






		}
		else
		{	
			//printf("ERROR: File error Both intiFlag and beaconFlag are false");
		}

		


	}

	if((!portFlag) || (!locFlag) || (!homedirFlag) )
	{
		printf("ERROR: ALL the mandatory fields do not exit in the INIT file. Node will terminate.\n\n");
		exit(0);

	}

	fclose(initFile);
	return;

}
